const ci = require('miniprogram-ci');
const path = require('path');
const fs = require('fs');

// 配置信息
const config = {
  appid: '{{{{wechat_appid}}}}', // 从project.config.json中获取的appid
  projectPath: __dirname, // 当前目录作为项目路径
  privateKeyPath: path.resolve(__dirname, 'private.{{{{wechat_appid}}}}.key'), // 私钥路径
  version: '1.0.0', // 版本号，可以根据需要修改
  desc: '自动上传体验版' // 上传描述
};

// 获取当前时间作为版本描述
function getTimeDesc() {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes} 自动上传`;
}

// 主要上传函数
async function uploadToWeChat() {
  try {
    console.log('开始上传小程序到体验版...');
    console.log('项目路径:', config.projectPath);
    console.log('AppID:', config.appid);
    
    // 检查私钥文件是否存在
    if (!fs.existsSync(config.privateKeyPath)) {
      throw new Error(`私钥文件不存在: ${config.privateKeyPath}`);
    }
    
    // 创建项目实例
    const project = new ci.Project({
      appid: config.appid,
      type: 'miniProgram',
      projectPath: config.projectPath,
      privateKeyPath: config.privateKeyPath,
      ignores: ['node_modules/**/*', '*.log', '.git/**/*']
    });
    
    console.log('项目实例创建成功，开始上传...');
    
    // 上传代码
    const uploadResult = await ci.upload({
      project,
      version: config.version,
      desc: getTimeDesc(),
      setting: {
        es6: true,
        minifyJS: true,
        minifyWXML: true,
        minifyWXSS: true,
        minify: true
      },
      onProgressUpdate: (progress) => {
        console.log('上传进度:', progress);
      }
    });
    
    console.log('上传成功！');
    console.log('上传结果:', uploadResult);
    
  } catch (error) {
    console.error('上传失败:', error.message);
    process.exit(1);
  }
}

// 预览功能（可选）
async function previewWeChat() {
  try {
    console.log('开始生成预览二维码...');
    
    // 检查私钥文件是否存在
    if (!fs.existsSync(config.privateKeyPath)) {
      throw new Error(`私钥文件不存在: ${config.privateKeyPath}`);
    }
    
    // 创建项目实例
    const project = new ci.Project({
      appid: config.appid,
      type: 'miniProgram',
      projectPath: config.projectPath,
      privateKeyPath: config.privateKeyPath,
      ignores: ['node_modules/**/*', '*.log', '.git/**/*']
    });
    
    // 生成预览
    const previewResult = await ci.preview({
      project,
      version: config.version,
      desc: getTimeDesc(),
      setting: {
        es6: true,
        minifyJS: true,
        minifyWXML: true,
        minifyWXSS: true,
        minify: true
      },
      qrcodeFormat: 'image',
      qrcodeOutputDest: path.resolve(__dirname, 'preview-qrcode.jpg'),
      onProgressUpdate: (progress) => {
        console.log('预览进度:', progress);
      }
    });
    
    console.log('预览二维码生成成功！');
    console.log('二维码保存路径:', path.resolve(__dirname, 'preview-qrcode.jpg'));
    
  } catch (error) {
    console.error('预览失败:', error.message);
    process.exit(1);
  }
}

// 命令行参数处理
const args = process.argv.slice(2);
const command = args[0];

switch (command) {
  case 'upload':
    uploadToWeChat();
    break;
  case 'preview':
    previewWeChat();
    break;
  default:
    console.log('使用方法:');
    console.log('  node upload.js upload   - 上传到体验版');
    console.log('  node upload.js preview  - 生成预览二维码');
    break;
}